package com.springboot.util.string;

import cn.hutool.core.util.StrUtil;
import com.springboot.util.common.MyUtilException;
import com.springboot.util.enums.RespErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;

/**
 * @description:
 * @author: zyj
 * @create: 2020-08-13 15:26
 **/
@Slf4j
public class MyStringUtil {

    private static String del_null = "\\s*|\t|\r|\n";

    // 身份证校验码
    private static final int[] COEFFICIENT_ARRAY = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

    // 身份证号的尾数规则
    private static final String[] IDENTITY_MANTISSA = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};

    private static final String IDENTITY_PATTERN = "^[0-9]{17}[0-9Xx]$";


    public static String replaceBlank(String str) {

        String dest = "";
        if (str != null) {
            Pattern pattern = Pattern.compile(del_null);
            Matcher m = pattern.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 去除首尾指定字符
     *
     * @param str     字符串
     * @param element 指定字符
     * @return
     */
    public static String trimFirstAndLastChar(String str, String element) {
        boolean beginIndexFlag = true;
        boolean endIndexFlag = true;
        do {
            int beginIndex = str.indexOf(element) == 0 ? 1 : 0;
            int endIndex = str.lastIndexOf(element) + 1 == str.length() ? str.lastIndexOf(element) : str.length();
            str = str.substring(beginIndex, endIndex);
            beginIndexFlag = (str.indexOf(element) == 0);
            endIndexFlag = (str.lastIndexOf(element) + 1 == str.length());
        } while (beginIndexFlag || endIndexFlag);
        return str;
    }

    /**
     * 处理特殊字符问题
     *
     * @param phone
     * @return
     */
    public static String dealBlankString(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            phone = removeNonAscii(phone);
            phone = removeSomeControlChar(phone);
            phone = removeFullControlChar(phone).trim();
            return phone;
        }
        return null;
    }

    /**
     * 去除非ascii码字符
     *
     * @param str
     * @return
     */
    public static String removeNonAscii(String str) {
        return str.replaceAll("[^\\x00-\\x7F]", "");
    }

    /**
     * 去除不可打印字符
     *
     * @param str
     * @return
     */
    public static String removeNonPrintable(String str) {
        return str.replaceAll("[\\p{C}]", "");
    }

    /**
     * 去除一些控制字符 Control Char
     *
     * @param str
     * @return
     */
    public static String removeSomeControlChar(String str) {
        return str.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", ""); // Some Control Char
    }

    /**
     * 去除一些换行制表符
     *
     * @param str
     * @return
     */
    public static String removeFullControlChar(String str) {
        return removeNonPrintable(str).replaceAll("[\\r\\n\\t]", "");
    }


    /**
     * @Description: 生成随机数
     * @Param: [size 多少位]
     * @return: java.lang.String
     * @Author: zyj
     * @Date: 2020/9/21
     */
    public static String randomStr(int size) {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < size; i++) {
            result += random.nextInt(10);
        }
        return result;
    }


    /**
     * @Description: 去除字符串
     * @Param: [str, indexStr]
     * @return: java.lang.String
     * @Author: zyj
     * @Date: 2020/9/27
     */
    public static String trimStr(String str, String indexStr) {
        if (str == null) {
            return null;
        }
        StringBuilder newStr = new StringBuilder(str);
        //在开头
        if (newStr.indexOf(indexStr) == 0) {
            newStr = new StringBuilder(newStr.substring(indexStr.length()));

        }
        //在结尾
        else if (newStr.indexOf(indexStr) == newStr.length() - indexStr.length()) {
            newStr = new StringBuilder(newStr.substring(0, newStr.lastIndexOf(indexStr)));

        }
        //在中间　
        else if (newStr.indexOf(indexStr) < (newStr.length() - indexStr.length())) {
            newStr = new StringBuilder(newStr.substring(0, newStr.indexOf(indexStr)) + newStr.substring(newStr.indexOf(indexStr) + indexStr.length(), newStr.length()));

        }
        return newStr.toString();
    }


    public static boolean isLegalPattern(String identity) {
        if (identity == null) {
            return false;
        }

        if (identity.length() != 18) {
            return false;
        }

        if (!identity.matches(IDENTITY_PATTERN)) {
            return false;
        }

        char[] chars = identity.toCharArray();
        long sum = IntStream.range(0, 17).map(index -> {
            char ch = chars[index];
            int digit = Character.digit(ch, 10);
            int coefficient = COEFFICIENT_ARRAY[index];
            return digit * coefficient;
        }).summaryStatistics().getSum();

        // 计算出的尾数索引
        int mantissaIndex = (int) (sum % 11);
        String mantissa = IDENTITY_MANTISSA[mantissaIndex];

        String lastChar = identity.substring(17);
        if (lastChar.equalsIgnoreCase(mantissa)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 如果dto中String类型的变量="", 将该变量值改为null
     *
     * @param source
     * @param <T>
     * @return
     * @author zyj
     * @date 2020/8/20
     */
    public static <T> T setNullValue(T source) {
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getGenericType().toString().equals("class java.lang.String")) {
                field.setAccessible(true);
                try {
                    Object obj = field.get(source);
                    if (obj != null && obj.equals("")) {
                        field.set(source, null);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return source;
    }


    /**
     * 方法描述 替换文本
     *
     * @param content
     * @param replaceValue
     * @since: 1.0
     * @return: String
     * @author: zyj
     * @date: 2023/5/17 18:02
     */
    public static String replaceAllStr(String content, Map<String, String> replaceValue) throws MyUtilException {
        Iterator<Map.Entry<String, String>> replaceIte = replaceValue.entrySet().iterator();
        String result = "";
        while (replaceIte.hasNext()) {

            Map.Entry<String, String> entry = replaceIte.next();
            String key = entry.getKey();
            String value = entry.getValue();
            try {
                if (StrUtil.isNotEmpty(content)) {
                    result = content.replaceAll(key, value);
                }
                content = result;
            } catch (Exception e) {
                log.error("replaceAllStr error", e);
                throw new MyUtilException(RespErrorCode.TEMP_REPLACE_ERROR.getValue(), RespErrorCode.TEMP_REPLACE_ERROR.getDescripe());
            }

        }

        return content;
    }

}
